package wubj.com.uploaddemo;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import wubj.com.uploaddemo.application.MyBaseActivity;
import wubj.com.uploaddemo.bean.ChatMsg;
import wubj.com.uploaddemo.bean.CommonItemBean;
import wubj.com.uploaddemo.bean.MediaBean;
import wubj.com.uploaddemo.upload.IuploadListener;
import wubj.com.uploaddemo.upload.UploadMg;
import wubj.com.uploaddemo.utils.CloseUtils;
import wubj.com.uploaddemo.utils.DateUtils;
import wubj.com.uploaddemo.utils.LogUtil;
import wubj.com.uploaddemo.utils.ResourceUtils;
import wubj.com.uploaddemo.view.BottomSelectDialog;

public class MainActivity extends MyBaseActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    public static final int ITEM_PICTURE = 1;
    public static final int ITEM_TAKE_PICTURE = 2;
    private static final String IMAGE_ADDRESS = Environment.getExternalStorageDirectory() + File.separator + "wubj";

    public static final String IP = "http://222.173.29.164:81"; //新接口地址
    private static final String URL_SUFFIX = IP + "/AFMIS/";// 现网地址
    public static final String upLoadFileCommon = URL_SUFFIX + "upLoadFileCommon";//工日志文件上传

    private String userId = "77cfc538-dd58-46d0-b1ae-138110e27e1c";

    private File cameraFile;
    private ImageView ivUpload;

    @Override
    public void initView() {
        setContentView(R.layout.activity_main);
        Button btUpload = (Button) findViewById(R.id.bt_upload);
        ivUpload = (ImageView) findViewById(R.id.iv_upload);
        btUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPhotoDialog();
            }
        });
        File file = new File(IMAGE_ADDRESS);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public void showPhotoDialog() {
        List<CommonItemBean> list = new ArrayList<>();
        list.add(new CommonItemBean(getString(R.string.choose_a_pic), 0));
        list.add(new CommonItemBean(getString(R.string.take_a_pic), 1));
        BottomSelectDialog dialog = new BottomSelectDialog.Builder(mContext).build();
        dialog.setSingleChoiceItems(list, new BottomSelectDialog.ISelectItemListener() {
            @Override
            public void clickListener(View view, CommonItemBean bean, int position) {
                switch (bean.tag) {
                    case 0: //拍照
                        selectPicFromLocal();
                        break;
                    case 1: //本地选择照片
                        selectPicFromCamera();
                        break;
                }
            }
        }).show();
    }

    /**
     * 从相册选择图片
     */
    private void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) { //api 19 and later, we can't use this way, demo just select from images
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, ITEM_PICTURE);
    }

    /**
     * capture new image
     */
    protected void selectPicFromCamera() {
        if (!ResourceUtils.isSdcardExist()) {
            Toast.makeText(mContext, R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }
        String name = System.currentTimeMillis() + ".jpg";
        LogUtil.d(TAG, "camera name " + name);
        cameraFile = new File(IMAGE_ADDRESS, name);
        //noinspection ResultOfMethodCallIgnored
        cameraFile.getParentFile().mkdirs();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
        startActivityForResult(intent, ITEM_TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.d(TAG, "wubaojie>>>onActivityResult: resultCode:" + requestCode);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == ITEM_TAKE_PICTURE) { // 拍照
                if (cameraFile != null && cameraFile.exists()) {
                    LogUtil.d(TAG, "wubaojie>>>onActivityResult: Path:" + cameraFile.getAbsolutePath());
                    LogUtil.d(TAG, "wubaojie>>>onActivityResult: Name:" + cameraFile.getName());

                    MediaBean mediaBean = new MediaBean();
                    mediaBean.insert_time = String.valueOf(System.currentTimeMillis());
                    mediaBean.file_name = cameraFile.getName();
                    mediaBean.file_type = "0";
                    mediaBean.file_state = "0";
                    mediaBean.path_type = "0";
                    mediaBean.content = cameraFile.getAbsolutePath();
                    mediaBean.pic_shoot_time = System.currentTimeMillis() + "";
                    updatePic(mediaBean);
                }
            } else if (requestCode == ITEM_PICTURE) { //相册选择图片
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }
            }
        }
    }

    protected ArrayList<ChatMsg> uploadList = new ArrayList<>();

    private void updatePic(MediaBean mediaBean) {
        if ("0".equals(mediaBean.file_state)) {
            ChatMsg info = new ChatMsg();
            info.mFileType = mediaBean.file_type;
            info.fileType = mediaBean.content_type;//后缀名
            info.mSendTime = DateUtils.getNowDateTime();
            info.msgId = System.currentTimeMillis();
            info.fromUser = userId;
            info.mUUID = userId;
            info.platForm = "worklog";
            info.fileName = mediaBean.file_name;
            info.imgPath = mediaBean.content;
            info.picShootTime = mediaBean.pic_shoot_time;

            if (TextUtils.isEmpty(info.fileType) && !TextUtils.isEmpty(info.fileName)) {
                info.fileType = info.fileName.substring(info.fileName.indexOf(".") + 1, info.fileName
                        .length());
            }
            info.uploadUrl = upLoadFileCommon;
            uploadList.add(info);
            UploadMg.getInstance().uploadFile(uploadList, iuploadListener);
        }
    }

    IuploadListener iuploadListener = new IuploadListener() {
        @Override
        public void onUploadBefore(ChatMsg uploads) {

        }

        @Override
        public void onUploading(int position, long uploaded, long total, float progress, float speed, ChatMsg
                uploads, int current) {
            showWaitDialog("正在上传图片");
        }

        @Override
        public void onUploadError(int position, long uploaded, float progress, ChatMsg uploads, int current) {
        }

        @Override
        public void onUploadAllFinished(int position, final ChatMsg uploads, boolean checkFlag) {
            hideWaitDialog();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final String url = uploads.mContent;
                    LogUtil.e(TAG, "wubaojie>>>onUploadAllFinished: 返回图片地址:" + url);
                    Picasso.with(mContext).load(url).into(ivUpload);
                }
            });
        }

        @Override
        public void onCancelUpload(int position, ChatMsg uploads, int current) {

        }

        @Override
        public void onPauseUpload(int position, ChatMsg uploads, int current) {

        }

        @Override
        public void onResumeUpload(int position, ChatMsg uploads, int current) {

        }
    };

    /**
     * 相册中选择图片
     *
     * @param uri
     */
    protected void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
                CloseUtils.closeIO(cursor);
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        if (filePath == null) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            Toast.makeText(mContext, R.string.file_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }
        if (file.length() > 10 * 1024 * 1024) {
            Toast.makeText(mContext, R.string.file_is_not_greater_than_10_m, Toast
                    .LENGTH_SHORT).show();
            return;
        }
        MediaBean mediaBean = new MediaBean();
        mediaBean.insert_time = String.valueOf(System.currentTimeMillis());
        mediaBean.file_name = file.getName();
        mediaBean.file_type = "0";
        mediaBean.file_state = "0";
        mediaBean.path_type = "0";
        mediaBean.content = file.getAbsolutePath();
        updatePic(mediaBean);
    }

}
